import React, { useState, useRef, useEffect } from 'react';
import { Paperclip, Send } from 'lucide-react';
import { useFileUpload } from '../../hooks';

interface MessageInputProps {
  onSendMessage: (content: string) => void;
  disabled?: boolean;
  placeholder?: string;
  className?: string;
}

export function MessageInput({
  onSendMessage,
  disabled = false,
  placeholder = '发消息、输入@选择技能或/选择文件',
  className = '',
}: MessageInputProps) {
  const [message, setMessage] = useState('');
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { uploadFile, isUploading } = useFileUpload();
  
  // 自动调整textarea高度
  const adjustTextareaHeight = () => {
    const textarea = textareaRef.current;
    if (textarea) {
      textarea.style.height = 'auto';
      textarea.style.height = `${Math.min(textarea.scrollHeight, 200)}px`;
    }
  };
  
  useEffect(() => {
    adjustTextareaHeight();
  }, [message]);
  
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const trimmedMessage = message.trim();
    if (!trimmedMessage || disabled) return;
    
    console.log('Sending message:', trimmedMessage);
    onSendMessage(trimmedMessage);
    
    // 清空消息
    setMessage('');
    console.log('Message cleared, current state:', message);
    
    // 重置textarea高度
    setTimeout(() => {
      if (textareaRef.current) {
        textareaRef.current.style.height = 'auto';
      }
    }, 0);
  };
  
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit(e);
    }
  };
  
  const handleFileSelect = async (file: File) => {
    try {
      await uploadFile(file);
    } catch (error) {
      console.error('File upload failed:', error);
    }
  };
  
  const handleFileButtonClick = () => {
    fileInputRef.current?.click();
  };
  
  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length > 0) {
      Promise.allSettled(files.map(f => handleFileSelect(f)));
      // 清空input值，允许重复选择同一文件
      e.target.value = '';
    }
  };

  // 监听自定义文件事件（由 priorityEventBlocker 触发）
  useEffect(() => {
    const handleCustomFileEvent = (event: Event) => {
      console.log('📁 MessageInput 收到自定义文件事件:', event.type);
      const customEvent = event as CustomEvent<{ files: File[] }>;
      if (customEvent.detail?.files) {
        const files = Array.from(customEvent.detail.files);
        console.log('📁 文件数量:', files.length);
        if (files.length > 0) {
          Promise.allSettled(files.map(f => handleFileSelect(f)));
        }
      }
    };

    document.addEventListener('rc-file-change', handleCustomFileEvent as EventListener);
    document.addEventListener('rc-file-paste', handleCustomFileEvent as EventListener);
    document.addEventListener('rc-file-drop', handleCustomFileEvent as EventListener);

    return () => {
      document.removeEventListener('rc-file-change', handleCustomFileEvent as EventListener);
      document.removeEventListener('rc-file-paste', handleCustomFileEvent as EventListener);
      document.removeEventListener('rc-file-drop', handleCustomFileEvent as EventListener);
    };
  }, []);
  
  const handlePaste = (e: React.ClipboardEvent) => {
    const items = Array.from(e.clipboardData.items);
    const fileItem = items.find(item => item.kind === 'file');
    
    if (fileItem) {
      e.preventDefault();
      const file = fileItem.getAsFile();
      if (file) {
        handleFileSelect(file);
      }
    }
  };
  
  return (
    <div className={`border-t bg-white ${className}`}>
      {/* 隐藏的文件输入 - 移除原生onChange，使用自定义事件 */}
      <input
        ref={fileInputRef}
        type="file"
        multiple
        className="hidden"
        data-app="react-chat"
      />
      
      {/* 输入区域 */}
      <form onSubmit={handleSubmit} className="p-4">
        {/* 输入框容器 - 包裹所有元素 */}
        <div className="bg-white border-2 border-gray-200 rounded-xl focus-within:border-blue-500 transition-colors shadow-sm">
          {/* 文本输入区域 */}
          <div className="p-3 pb-0">
            <textarea
              ref={textareaRef}
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              onKeyDown={handleKeyDown}
              onPaste={handlePaste}
              placeholder={placeholder}
              disabled={disabled}
              rows={1}
              className="w-full resize-none border-none outline-none bg-transparent disabled:opacity-50 disabled:cursor-not-allowed placeholder-gray-400 text-xs min-h-6 max-h-50"
            />
          </div>
          
          {/* 底部操作栏 */}
          <div className="flex items-center justify-between px-3 py-2">
            {/* 左侧：附件按钮 */}
            <button
              type="button"
              onClick={handleFileButtonClick}
              disabled={disabled}
              className="w-8 h-8 rounded-full bg-white hover:bg-gray-100 border border-gray-200 flex items-center justify-center text-gray-600 hover:text-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
              title="上传文件"
            >
              <Paperclip className="w-4 h-4" />
            </button>
            
            {/* 中间：可以添加其他功能按钮 */}
            <div className="flex items-center space-x-2">
              {/* 这里可以添加深度思考、咕技能等按钮 */}
            </div>
            
            {/* 右侧：发送按钮 */}
            <button
              type="submit"
              disabled={!message.trim() || disabled}
              className={`w-8 h-8 rounded-full flex items-center justify-center transition-all duration-200 shadow-sm border ${
                message.trim() 
                  ? 'bg-blue-500 hover:bg-blue-600 text-white border-blue-500' 
                  : 'bg-white text-gray-400 border-gray-200'
              } disabled:bg-gray-200 disabled:cursor-not-allowed`}
              title="发送消息"
            >
              <Send className="w-4 h-4" />
            </button>
          </div>
        </div>
        
        {/* 状态提示 */}
        {isUploading && (
          <div className="mt-3 text-xs text-blue-600 text-center">
            文件上传中...
          </div>
        )}
      </form>
    </div>
  );
}